﻿namespace Away.Jobs.Services.Implements;

public class JobService : IJobService
{
    private readonly IScheduler _scheduler;
    private readonly IJobRepository _jobRepository;
    public JobService(ISchedulerFactory schedulerFactory, IJobRepository jobRepository)
    {
        _scheduler = AsyncHelper.RunSync(() => schedulerFactory.GetScheduler());
        _jobRepository = jobRepository;
    }

    public ApiResult GetJobPage(JobSearch search)
    {
        return _jobRepository.GetJobPage(search);
    }
    public async Task<List<string>> GetJobGroupList()
    {
        return (await _scheduler.GetJobGroupNames()).ToList();
    }
    public async Task AddJob(JobDetail jobDetail)
    {
        jobDetail.IsDurable = true;
        await _scheduler.AddJob(jobDetail.Job, false);
    }
    public async Task UpdateJob(JobDetail jobDetail)
    {
        jobDetail.IsDurable = true;
        await _scheduler.AddJob(jobDetail.Job, true);
    }
    public Task StartJob(string group)
    {
        return _scheduler.ResumeJobs(GroupMatcher<JobKey>.GroupEquals(group));
    }
    public Task StopJob(string group)
    {
        return _scheduler.PauseJobs(GroupMatcher<JobKey>.GroupEquals(group));
    }
    public async Task StartJob(List<Key> jobKeys)
    {
        var tasks = jobKeys.Select(o => _scheduler.ResumeJob(o.JobKey)).ToArray();
        await Task.WhenAll(tasks);
    }
    public async Task StopJob(List<Key> jobKeys)
    {

        var tasks = jobKeys.Select(o => _scheduler.PauseJob(o.JobKey)).ToArray();
        await Task.WhenAll(tasks);
    }
    public Task DeleteJob(List<Key> jobKeys)
    {
        return _scheduler.DeleteJobs(jobKeys.Select(o => o.JobKey).ToList());
    }
    public Task RunJob(Key jobKey)
    {
        return _scheduler.TriggerJob(jobKey.JobKey);
    }
    public Task CancelJob(Key jobKey)
    {
        return _scheduler.Interrupt(jobKey.JobKey);
    }
}
